package gdufs.lkl.calculator;

import android.content.Context;
import android.util.Log;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 计算历史记录管理类
 * 负责保存、读取、管理计算历史记录
 */
public class CalculationHistory {
    private static final String TAG = "CalculationHistory";
    private static final String HISTORY_FILE_NAME = "calculation_history.txt";
    
    private static CalculationHistory instance;
    private Context context;
    private List<HistoryEntry> historyList;
    private SettingsManager settingsManager;
    
    /**
     * 历史记录条目
     */
    public static class HistoryEntry {
        public String expression;
        public String result;
        public String timestamp;
        public String calculatorType; // "basic" 或 "scientific"
        
        public HistoryEntry(String expression, String result, String calculatorType) {
            this.expression = expression;
            this.result = result;
            this.calculatorType = calculatorType;
            this.timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(new Date());
        }
        
        @Override
        public String toString() {
            return expression + " = " + result;
        }
        
        public String toFileString() {
            return timestamp + "|" + calculatorType + "|" + expression + "|" + result;
        }
        
        public static HistoryEntry fromFileString(String line) {
            try {
                String[] parts = line.split("\\|");
                if (parts.length >= 4) {
                    HistoryEntry entry = new HistoryEntry(parts[2], parts[3], parts[1]);
                    entry.timestamp = parts[0];
                    return entry;
                }
            } catch (Exception e) {
                Log.e(TAG, "解析历史记录失败: " + line, e);
            }
            return null;
        }
    }
      private CalculationHistory(Context context) {
        this.context = context.getApplicationContext();
        this.settingsManager = SettingsManager.getInstance(context);
        this.historyList = new ArrayList<>();
        loadHistory();
    }
    
    /**
     * 获取历史记录管理实例
     */
    public static CalculationHistory getInstance(Context context) {
        if (instance == null) {
            instance = new CalculationHistory(context);
        }
        return instance;
    }
    
    /**
     * 添加历史记录
     */
    public void addHistory(String expression, String result, String calculatorType) {
        if (expression == null || expression.trim().isEmpty() || 
            result == null || result.trim().isEmpty()) {
            return;
        }
        
        HistoryEntry entry = new HistoryEntry(expression.trim(), result.trim(), calculatorType);
        
        // 避免重复记录相同的计算
        if (!historyList.isEmpty()) {
            HistoryEntry lastEntry = historyList.get(historyList.size() - 1);
            if (lastEntry.expression.equals(entry.expression) && 
                lastEntry.result.equals(entry.result)) {
                return;
            }
        }
          historyList.add(entry);
        
        // 限制历史记录数量（使用设置中的值）
        int maxHistoryCount = settingsManager.getHistoryMaxCount();
        while (historyList.size() > maxHistoryCount) {
            historyList.remove(0);
        }
        
        saveHistory();
    }
    
    /**
     * 获取所有历史记录
     */
    public List<HistoryEntry> getHistory() {
        return new ArrayList<>(historyList);
    }
    
    /**
     * 获取最近的历史记录
     */
    public List<HistoryEntry> getRecentHistory(int count) {
        List<HistoryEntry> recent = new ArrayList<>();
        int start = Math.max(0, historyList.size() - count);
        for (int i = start; i < historyList.size(); i++) {
            recent.add(historyList.get(i));
        }
        return recent;
    }
    
    /**
     * 清空所有历史记录
     */
    public void clearHistory() {
        historyList.clear();
        saveHistory();
        Log.d(TAG, "清空历史记录");
    }
    
    /**
     * 删除指定的历史记录
     */
    public void removeHistory(int index) {
        if (index >= 0 && index < historyList.size()) {
            historyList.remove(index);
            saveHistory();
        }
    }
    
    /**
     * 从文件加载历史记录
     */
    private void loadHistory() {
        try (FileInputStream fis = context.openFileInput(HISTORY_FILE_NAME);
             InputStreamReader isr = new InputStreamReader(fis);
             BufferedReader br = new BufferedReader(isr)) {
            
            String line;
            while ((line = br.readLine()) != null) {
                HistoryEntry entry = HistoryEntry.fromFileString(line);
                if (entry != null) {
                    historyList.add(entry);
                }
            }
            
            Log.d(TAG, "加载历史记录: " + historyList.size() + " 条");
        } catch (IOException e) {
            Log.d(TAG, "历史记录文件不存在或读取失败，将创建新文件");
        }
    }
    
    /**
     * 保存历史记录到文件
     */
    private void saveHistory() {
        try (FileOutputStream fos = context.openFileOutput(HISTORY_FILE_NAME, Context.MODE_PRIVATE);
             OutputStreamWriter osw = new OutputStreamWriter(fos)) {
            
            for (HistoryEntry entry : historyList) {
                osw.write(entry.toFileString() + "\n");
            }
            
            Log.d(TAG, "保存历史记录: " + historyList.size() + " 条");
        } catch (IOException e) {
            Log.e(TAG, "保存历史记录失败", e);
        }
    }
    
    /**
     * 获取历史记录总数
     */
    public int getHistoryCount() {
        return historyList.size();
    }
    
    /**
     * 检查是否有历史记录
     */
    public boolean hasHistory() {
        return !historyList.isEmpty();
    }
}
